<template>
  <div class="add-lesson-type-bg">
    <!-- 返回按钮 -->
    <div class="back-btn-bar">
      <button class="back-btn" @click="goBackToCategory">
        <el-icon><ArrowLeft /></el-icon> 返回课程分类管理
      </button>
    </div>
    <div class="add-lesson-type-page">
      <div class="page-header">
        <h2 class="page-title">新增课程分类</h2>
        <p class="page-desc">
          请填写课程分类的相关信息，带 <span class="required">*</span> 为必填项
        </p>
      </div>

      <el-form
        :model="form"
        label-width="120px"
        class="add-form"
        :rules="rules"
        ref="formRef"
      >
        <el-form-item label="分类名称" prop="lessonType" class="form-item">
          <el-input
            v-model="form.lessonType"
            placeholder="请输入课程分类名称（如：无人机操作基础）"
            class="form-input"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>

        <el-form-item
          label="分类描述"
          prop="lessonTypeDescription"
          class="form-item"
        >
          <el-input
            v-model="form.lessonTypeDescription"
            type="textarea"
            placeholder="请详细描述该课程分类的内容、适用人群等信息"
            class="form-textarea"
            :rows="4"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>

        <el-form-item
          label="分类图片"
          prop="file"
          class="form-item upload-item"
        >
          <ImageUploadWithValidation
            v-model="form.file"
            v-model:imageUrl="form.fileUrl"
            :required="true"
            button-text="选择图片"
            tip-text="建议上传JPG、PNG格式的图片，大小不超过2MB"
            :max-size="2"
            :allowed-formats="[
              'image/jpeg',
              'image/jpg',
              'image/png',
              'image/gif',
            ]"
            @change="handleImageChange"
            ref="imageUpload"
          />
        </el-form-item>

        <el-form-item class="form-actions">
          <el-button
            type="primary"
            @click="submit"
            class="submit-btn"
            :disabled="!canSubmit"
          >
            <i class="el-icon-check"></i> 提交
          </el-button>
          <el-button @click="goBack" class="cancel-btn">
            <i class="el-icon-arrow-left"></i> 取消
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { ArrowLeft } from "@element-plus/icons-vue";
import axios from "axios";
import ImageUploadWithValidation from "../../components/ImageUploadWithValidation.vue";

const router = useRouter();
const formRef = ref(null);

const form = reactive({
  lessonType: "",
  lessonTypeDescription: "",
  file: null,
  fileUrl: "",
});

// 表单验证规则
const rules = {
  lessonType: [
    { required: true, message: "请输入分类名称", trigger: "blur" },
    {
      min: 2,
      max: 50,
      message: "分类名称长度在2-50个字符之间",
      trigger: "blur",
    },
  ],
  lessonTypeDescription: [
    { required: true, message: "请输入分类描述", trigger: "blur" },
    {
      min: 10,
      max: 500,
      message: "分类描述长度在10-500个字符之间",
      trigger: "blur",
    },
  ],
  file: [{ required: true, message: "请上传分类图片", trigger: "change" }],
};

// 图片上传前校验 - 已移至 ImageUploadWithValidation 组件
// const beforeUpload = (file) => {
//   const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
//   const isLt2M = file.size / 1024 / 1024 < 2;

//   if (!isJpgOrPng) {
//     ElMessage.error("上传图片只能是 JPG/PNG 格式!");
//     return false;
//   }
//   if (!isLt2M) {
//     ElMessage.error("上传图片大小不能超过 2MB!");
//     return false;
//   }
//   return true;
// };

const handleImageChange = () => {
  // 这个方法现在由 ImageUploadWithValidation 组件内部处理
  // 不需要额外的逻辑，因为组件已经通过 v-model 绑定了数据
};

// 计算属性：是否可以提交
const canSubmit = computed(() => {
  // 检查是否已上传图片
  if (!form.file) {
    return false;
  }

  // 检查是否有图片验证错误
  try {
    const imageUploadRef = formRef.value?.$refs?.imageUpload;
    if (
      imageUploadRef &&
      typeof imageUploadRef.hasError === "function" &&
      imageUploadRef.hasError()
    ) {
      return false;
    }
  } catch (error) {
    // 如果获取引用失败，保守起见返回 false
    return false;
  }

  return true;
});

// 移除图片功能已移至 ImageUploadWithValidation 组件
// const removeImage = () => {
//   form.file = null;
//   form.fileUrl = "";
// };

const submit = async () => {
  try {
    // 表单验证
    await formRef.value.validate();

    // 检查必需的文件是否已上传
    if (!form.file) {
      ElMessage.error("请上传分类图片");
      return;
    }

    // 获取图片上传组件的引用进行验证
    const imageUploadRef = formRef.value.$refs?.imageUpload;
    if (imageUploadRef && imageUploadRef.hasError()) {
      ElMessage.error("请选择符合要求的图片");
      return;
    }

    const formData = new FormData();
    formData.append("lessonType", form.lessonType);
    formData.append("file", form.file);

    const res = await axios.post(
      "/tielingpowergriduavservice/lesson-type/add",
      formData
    );
    if (res.data.code === 200) {
      ElMessage.success("新增成功");
      router.back();
    } else {
      ElMessage.error("新增失败：" + res.data.msg);
    }
  } catch (e) {
    ElMessage.error("请求异常：" + e.message);
  }
};

const goBack = () => {
  // 判断表单是否有修改
  if (form.lessonType || form.lessonTypeDescription || form.file) {
    ElMessageBox.confirm("当前表单内容未保存，确定要离开吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        router.back();
      })
      .catch(() => {
        // 取消离开
      });
  } else {
    router.back();
  }
};

const goBackToCategory = () => {
  router.push("/course-types?tab=category");
};
</script>

<style scoped>
.back-btn-bar {
  position: absolute;
  top: 38px;
  left: 60px;
  z-index: 10;
}

.back-btn {
  font-size: 16px;
  color: #3498db;
  background: #fff;
  border-radius: 20px;
  box-shadow: 0 2px 8px rgba(52, 152, 219, 0.08);
  padding: 8px 22px;
  border: none;
  transition: background 0.2s;
}

.back-btn:hover {
  background: #eaf6fb;
  color: #217dbb;
}

.add-lesson-type-bg {
  min-height: 100vh;
  width: 100vw;
  background: linear-gradient(135deg, #e0f7fa 0%, #f8fafc 60%, #d1e9fc 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}

.add-lesson-type-bg::before {
  content: "";
  position: absolute;
  left: -100px;
  top: 80px;
  width: 260px;
  height: 260px;
  background: radial-gradient(
    circle,
    #b2ebf2 0%,
    #e0f7fa 80%,
    transparent 100%
  );
  border-radius: 50%;
  z-index: 1;
  opacity: 0.5;
}

.add-lesson-type-bg::after {
  content: "";
  position: absolute;
  right: -80px;
  bottom: 60px;
  width: 200px;
  height: 200px;
  background: radial-gradient(
    circle,
    #90caf9 0%,
    #d1e9fc 80%,
    transparent 100%
  );
  border-radius: 50%;
  z-index: 1;
  opacity: 0.4;
}

.add-lesson-type-page {
  max-width: 800px;
  margin: 0 auto;
  background: #fff;
  padding: 38px 48px 32px 48px;
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(44, 62, 80, 0.13);
  position: relative;
  z-index: 2;
}

/* 页面头部 */
.page-header {
  margin-bottom: 30px;
  padding-bottom: 15px;
  border-bottom: 1px solid #f1f5f9;
}

.page-title {
  font-size: 22px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0 0 10px 0;
  display: flex;
  align-items: center;
}

.page-title::before {
  content: "";
  display: inline-block;
  width: 4px;
  height: 20px;
  background-color: #3498db;
  margin-right: 10px;
  border-radius: 2px;
}

.page-desc {
  font-size: 14px;
  color: #7f8c8d;
  margin: 0;
}

.required {
  color: #e74c3c;
  font-weight: bold;
}

/* 表单样式 */
.add-form {
  width: 100%;
}

.form-item {
  margin-bottom: 25px;
  transition: all 0.3s;
}

.form-input {
  width: 100%;
  height: 42px;
  border-radius: 6px;
  border-color: #e2e8f0;
  transition: all 0.3s;
}

.form-input:focus {
  border-color: #3498db;
  box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.1);
}

.form-textarea {
  width: 100%;
  border-radius: 6px;
  border-color: #e2e8f0;
  resize: vertical;
}

/* 上传区域 */
.upload-item {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 15px;
}

.upload-btn {
  background-color: #3498db;
  border-color: #3498db;
  transition: all 0.3s;
}

.upload-btn:hover {
  background-color: #2980b9;
  border-color: #2980b9;
}

.upload-preview {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-left: 120px;
  /* 与label宽度对齐 */
}

.preview-img {
  max-width: 200px;
  max-height: 120px;
  border-radius: 6px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 4px;
  border: 1px solid #f1f5f9;
}

.remove-img {
  color: #e74c3c;
  padding: 5px 10px;
  height: auto;
}

.remove-img:hover {
  color: #c0392b;
  background-color: rgba(231, 76, 60, 0.05);
}

.upload-tip {
  font-size: 12px;
  color: #95a5a6;
  margin: 5px 0 0 120px;
  /* 与label宽度对齐 */
  line-height: 1.5;
}

/* 按钮区域 */
.form-actions {
  margin-top: 40px;
  padding-top: 20px;
  border-top: 1px solid #f1f5f9;
  display: flex;
  justify-content: flex-start;
  gap: 15px;
}

.submit-btn {
  background-color: #3498db;
  border-color: #3498db;
  padding: 8px 24px;
  font-size: 14px;
}

.submit-btn:hover {
  background-color: #2980b9;
  border-color: #2980b9;
}

.submit-btn:disabled {
  background-color: #c0c4cc;
  border-color: #c0c4cc;
  cursor: not-allowed;
  opacity: 0.6;
}

.submit-btn:disabled:hover {
  background-color: #c0c4cc;
  border-color: #c0c4cc;
}

.cancel-btn {
  padding: 8px 24px;
  font-size: 14px;
  color: #7f8c8d;
  background-color: #f8fafc;
  border-color: #e2e8f0;
}

.cancel-btn:hover {
  background-color: #f1f5f9;
  color: #64748b;
  border-color: #cbd5e1;
}

/* 响应式适配 */
@media (max-width: 768px) {
  .add-lesson-type-page {
    margin: 15px;
    padding: 20px 15px;
  }

  /* .el-form {
    label-width: 100px;
  } */

  .upload-preview,
  .upload-tip {
    margin-left: 100px;
  }

  .form-actions {
    flex-direction: column;
  }

  .submit-btn,
  .cancel-btn {
    width: 100%;
  }
}

@media (max-width: 480px) {
  /* .el-form {
    label-width: 80px;
  } */

  .upload-preview,
  .upload-tip {
    margin-left: 80px;
  }

  .preview-img {
    max-width: 150px;
  }
}
</style>
